package ThreadDemo3;

/**
 * Created with IntelliJ IDEA.
 * Description:wait和notify使用案例
 * User: 阿宾
 * Date: 2025-03-27
 * Time: 09:32
 */
public class ThreadDemo7 {
    public static void main(String[] args) {
        //创建对象
        Object locker = new Object();

        Thread t1 = new Thread(()->{
            synchronized (locker){
                System.out.println("t1线程wait之前");
                try {
                    locker.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("t1线程wait之后");
            }
        });

        Thread t2 = new Thread(()->{

            try {
                //保证先让t1线程拿到锁，不然可能t2先拿到锁之后，先执行notify，那么wait就不能被唤醒了，所以先让t2线程休眠
                Thread.sleep(5000);
                synchronized (locker){
                    System.out.println("t2线程notify之前");
                    locker.notify();//notify方法没有声明异常，所以不用处理异常
                    System.out.println("t2线程notify之后");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        t1.start();
        t2.start();
    }
}
